package com.promise.jokerdream.ui.account

import android.content.Context
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.promise.jokerdream.R
import com.promise.jokerdream.database.UserDataManager
import com.promise.jokerdream.database.account.UserAccount
import com.promise.jokerdream.ui.components.UserAvatar
import com.promise.jokerdream.ui.components.DangerAlertDialog
import com.promise.jokerdream.ui.theme.AppSpacing
import com.promise.jokerdream.ui.theme.AppFontSizes
import com.promise.jokerdream.ui.toolbar.AppTopBar

/**
 * 账号管理页面
 */
@Composable
fun AccountManagementPage(
    context: Context,
    navController: NavHostController,
    onAddAccount: () -> Unit = {},
    onAccountSelected: (UserAccount) -> Unit = {}
) {
    val userDataManager = remember { UserDataManager.getInstance(context) }
    var accounts by remember { mutableStateOf<List<UserAccount>>(emptyList()) }
    var currentAccount by remember { mutableStateOf<UserAccount?>(null) }
    var swipedAccountId by remember { mutableStateOf<String?>(null) }
    val hasPopBack = remember { mutableStateOf(false) }
    
    // 防重入的返回函数
    fun handleBack() {
        if (!hasPopBack.value) {
            hasPopBack.value = true
            navController.popBackStack()
        }
    }
    
    // 加载账号列表和当前账号
    LaunchedEffect(Unit) {
        accounts = userDataManager.getAllUserAccounts()
        currentAccount = userDataManager.getCurrentAccount()
    }
    
    // 处理返回手势
    BackHandler {
        handleBack()
    }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(MaterialTheme.colorScheme.surface)
    ) {
        // 顶部导航栏
        AppTopBar(
            title = "账号管理",
            onBackClick = { handleBack() }
        )
        
        // 账号管理卡片
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .wrapContentHeight()
                .padding(AppSpacing.cardHorizontal),
            shape = RoundedCornerShape(AppSpacing.cardRadius),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.surface
            ),
            elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
        ) {
            if (accounts.isEmpty()) {
                // 空状态
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(200.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally,
                        modifier = Modifier.padding(32.dp)
                    ) {
                        Box(
                            modifier = Modifier
                                .size(80.dp)
                                .background(
                                    brush = Brush.radialGradient(
                                        colors = listOf(
                                            MaterialTheme.colorScheme.primary.copy(alpha = 0.1f),
                                            MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.05f)
                                        )
                                    ),
                                    CircleShape
                                ),
                            contentAlignment = Alignment.Center
                        ) {
                            Icon(
                                painter = painterResource(id = R.drawable.ic_people),
                                contentDescription = null,
                                modifier = Modifier.size(40.dp),
                                tint = MaterialTheme.colorScheme.primary
                            )
                        }
                        
                        Spacer(modifier = Modifier.height(20.dp))
                        
                        Text(
                            text = "暂无账号",
                            fontSize = AppFontSizes.h3,
                            fontWeight = FontWeight.Medium,
                            color = MaterialTheme.colorScheme.onSurface
                        )
                        
                        Spacer(modifier = Modifier.height(8.dp))
                        
                        Text(
                            text = "登录后会自动保存账号信息",
                            fontSize = AppFontSizes.mediumBody,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            textAlign = androidx.compose.ui.text.style.TextAlign.Center
                        )
                    }
                }
            } else {
                Column(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    // 账号列表
                    accounts.forEachIndexed { index, account ->
                        AccountItem(
                            account = account,
                            isCurrentAccount = currentAccount?.userId == account.userId,
                            isSwiped = swipedAccountId == account.userId,
                            onSelect = { 
                                onAccountSelected(account)
                                handleBack() // 切换账号后直接退出页面
                            },
                            onSwipeStart = { swipedAccountId = account.userId },
                            onSwipeEnd = { swipedAccountId = null },
                            onDelete = {
                                userDataManager.deleteUserAccount(account.userId)
                                accounts = userDataManager.getAllUserAccounts()
                                
                                if (accounts.isEmpty()) {
                                    // 如果没有账号了，返回到登录页面
                                    handleBack()
                                } else if (currentAccount?.userId == account.userId) {
                                    // 如果删除的是当前账号，切换到第一个账号
                                    val firstAccount = accounts.first()
                                    userDataManager.setCurrentAccount(firstAccount.userId)
                                    currentAccount = firstAccount
                                    onAccountSelected(firstAccount)
                                    handleBack() // 删除成功后直接退出页面
                                }
                                // 如果删除的不是当前账号，不需要特殊处理
                                swipedAccountId = null
                            }
                        )
                        
                        // 分隔线（除了最后一个）
                        if (index < accounts.size - 1) {
                            HorizontalDivider(
                                modifier = Modifier.padding(horizontal = 12.dp),
                                color = MaterialTheme.colorScheme.outline.copy(alpha = 0.1f),
                                thickness = 0.5.dp
                            )
                        }
                    }
                    
                    // 分隔线
                    if (accounts.isNotEmpty()) {
                        HorizontalDivider(
                            modifier = Modifier.padding(horizontal = 12.dp),
                            color = MaterialTheme.colorScheme.outline.copy(alpha = 0.1f),
                            thickness = 0.5.dp
                        )
                    }
                    
                    // 添加账号按钮
                    AddAccountItem(
                        onClick = {
                            onAddAccount()
                            handleBack() // 新建账号后直接退出页面
                        }
                    )
                }
            }
        }
    }
}

/**
 * 账号项组件
 */
@Composable
private fun AccountItem(
    account: UserAccount,
    isCurrentAccount: Boolean,
    isSwiped: Boolean,
    onSelect: () -> Unit,
    onSwipeStart: () -> Unit,
    onSwipeEnd: () -> Unit,
    onDelete: () -> Unit
) {
    var offsetX by remember { mutableStateOf(0f) }
    var showDeleteDialog by remember { mutableStateOf(false) }
    val swipeThreshold = 80f
    
    // 当其他账号项开始滑动时，重置当前项的滑动状态
    LaunchedEffect(isSwiped) {
        if (!isSwiped) {
            offsetX = 0f
        }
    }
    
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(72.dp) // 固定高度，防止UI变大
    ) {
        // 删除按钮背景 - 跟随手势左滑拉出
        if (offsetX < 0) {
            Box(
                modifier = Modifier
                    .height(72.dp) // 与账号项高度一致
                    .width((-offsetX).dp) // 跟随滑动距离动态调整宽度
                    .background(Color.Red)
                    .align(Alignment.CenterEnd)
            ) {
                IconButton(
                    onClick = { showDeleteDialog = true },
                    modifier = Modifier.align(Alignment.Center)
                ) {
                    Icon(
                        painter = painterResource(id = R.drawable.ic_delete),
                        contentDescription = "删除账号",
                        tint = Color.White,
                        modifier = Modifier.size(24.dp)
                    )
                }
            }
        }
        
        // 账号项
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .offset(x = offsetX.dp)
                .pointerInput(Unit) {
                    detectHorizontalDragGestures(
                        onDragStart = { onSwipeStart() },
                        onDragEnd = {
                            if (offsetX < -swipeThreshold/2) {
                                offsetX = -swipeThreshold
                            } else {
                                offsetX = 0f
                                onSwipeEnd()
                            }
                        }
                    ) { _, x ->
                        if (x < 0) {
                            offsetX = (offsetX + x).coerceAtLeast(-swipeThreshold)
                        } else if (offsetX < 0) {
                            offsetX = (offsetX + x).coerceAtMost(0f)
                        }
                    }
                }
                .clickable { 
                    if (offsetX == 0f) {
                        onSelect()
                    }
                }
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(12.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 头像
                UserAvatar(
                    userId = account.userId,
                    size = 40.dp
                )
                
                Spacer(modifier = Modifier.width(12.dp))
                
                // 账号信息
                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = account.username,
                        fontSize = AppFontSizes.largeBody,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.onSurface,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                    Spacer(modifier = Modifier.height(2.dp))
                    Text(
                        text = account.userId,
                        fontSize = AppFontSizes.smallBody,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                }
                
                // 当前账号标识
                if (isCurrentAccount) {
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            painter = painterResource(id = R.drawable.ic_check),
                            contentDescription = "当前账号",
                            tint = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.size(20.dp)
                        )
                    }
                }
            }
        }
    }
    
    // 删除确认对话框
    DangerAlertDialog(
        show = showDeleteDialog,
        title = "删除账号",
        content = "确定要删除账号 \"${account.username}\" ？",
        confirmText = "删除",
        cancelText = "取消",
        onDismiss = { showDeleteDialog = false },
        onConfirm = {
            onDelete()
            showDeleteDialog = false
        }
    )
}


/**
 * 添加账号项组件
 */
@Composable
private fun AddAccountItem(
    onClick: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onClick() }
            .padding(12.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // 添加图标
        Box(
            modifier = Modifier
                .size(40.dp)
                .background(
                    MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.3f),
                    CircleShape
                ),
            contentAlignment = Alignment.Center
        ) {
            Icon(
                painter = painterResource(id = R.drawable.ic_add),
                contentDescription = "添加账号",
                tint = MaterialTheme.colorScheme.primary,
                modifier = Modifier.size(20.dp)
            )
        }
        
        Spacer(modifier = Modifier.width(12.dp))
        
        // 添加账号文字
        Text(
            text = "添加账号",
            fontSize = AppFontSizes.largeBody,
            fontWeight = FontWeight.Medium,
            color = MaterialTheme.colorScheme.onSurface
        )
    }
}
